package com.rr.sc.utils;

import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    public static int getYear(int yearMonth) {
	return yearMonth / 100;
    }

    public static int getMonth(int yearMonth) {
	return yearMonth % 100;
    }

    public static int getYearMonth(Date date) {
	Calendar now = Calendar.getInstance();
	now.setTime(date);
	return now.get(Calendar.YEAR) * 100 + now.get(Calendar.MONTH) + 1;
    }

    public static int getPreviousMonth(int yearMonth) {
	int year = getYear(yearMonth);
	int month = getMonth(yearMonth);
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.YEAR, year);
	calendar.set(Calendar.MONTH, month - 1);
	calendar.set(Calendar.DAY_OF_MONTH, 1);
	calendar.add(Calendar.MONTH, -1);
	return getYearMonth(calendar.getTime());
    }

    public static int getNextMonth(int yearMonth) {
	int year = getYear(yearMonth);
	int month = getMonth(yearMonth);
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.YEAR, year);
	calendar.set(Calendar.MONTH, month - 1);
	calendar.set(Calendar.DAY_OF_MONTH, 1);
	calendar.add(Calendar.MONTH, 1);
	return getYearMonth(calendar.getTime());
    }

    public static Date getStartDate(int year, int month) {
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.YEAR, year);
	calendar.set(Calendar.MONTH, month - 1);
	calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
	calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMinimum(Calendar.HOUR_OF_DAY));
	calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE));
	calendar.set(Calendar.SECOND, calendar.getActualMinimum(Calendar.SECOND));
	calendar.set(Calendar.MILLISECOND, calendar.getActualMinimum(Calendar.MILLISECOND));
	return calendar.getTime();
    }

    public static Date getEndDate(int year, int month) {
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.YEAR, year);
	calendar.set(Calendar.MONTH, month - 1);
	calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
	calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
	calendar.set(Calendar.MINUTE, calendar.getActualMaximum(Calendar.MINUTE));
	calendar.set(Calendar.SECOND, calendar.getActualMaximum(Calendar.SECOND));
	calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND));
	return calendar.getTime();
    }

    public static int getCurrentMonth() {
	return getMonth(getYearMonth(new Date()));
    }

    public static int getCurrentYear() {
	return getYear(getYearMonth(new Date()));
    }
}
